package com.org.lg.wechat.handler;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.org.lg.wechat.builder.TextBuilder;
import com.org.lg.wechat.utils.JsonUtils;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public  class ScanHandler extends AbstractHandler {

	    @Override
	    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
	                                    Map<String, Object> context, WxMpService weixinService,
	                                    WxSessionManager sessionManager) throws WxErrorException {

	        this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());

	        String content = "收到信息内容：";
	        // 获取微信用户基本信息
	        try {
	            WxMpUser userWxInfo = weixinService.getUserService()
	                .userInfo(wxMessage.getFromUser(), null);
	            if (userWxInfo != null) {
	                // TODO 可以添加关注用户到本地数据库
	            	 content = "欢迎：" +userWxInfo.getNickname()+"的关注";// JsonUtils.toJson(userWxInfo);
	            }
	        } catch (WxErrorException e) {
	            if (e.getError().getErrorCode() == 48001) {
	                this.logger.info("该公众号没有获取用户信息权限！");
	            }
	        }

	        return new TextBuilder().build(content, wxMessage, weixinService);

	    }
}
